import Cookie from 'js-cookie'
import Vue from 'vue'
export default function ({ $axios, redirect }) {
  $axios.onRequest(config => {
    if (Cookie.get('practiceJwtToken')) {  // 判断是否存在token，如果存在的话，则每个http header都加上token
      config.headers.Authorization = `Bearer ${Cookie.get('practiceJwtToken')}`;
    }

    return config;
  },
    err => {
      return Promise.reject(err)
    })

  $axios.onError(error => {
    const code = parseInt(error.response && error.response.status)
    switch (code) {
      //错误代码
      case 401:
        sessionStorage.clear();
        redirect('/login/login')
        break;
      case 403:
        sessionStorage.clear();
        redirect('/login/login')
        break;
      case 404:
        sessionStorage.clear();
        break;
      case 500:
        Message.error("Server exception");
        break;
      case 502:
        Message.error("Bad Gateway");
        break;
      case 503:
        Message.error(error.message);
        break;
      case 504:
        Message.error(error.message);
        break;
      default:
        break;
    }
  },
    err => {
      return Promise.reject(err)
    })

  $axios.onResponse(response => {
    let code = response.status
    // if (true) {
    //   setTimeout(function () {
    //     redirect('/')
    //   }, 2000)
    // }
  },
    err => {
      return Promise.reject(err)
    }
  )
}
